package com.xingren.wms.admin;

import com.xingren.common.data.JsonResult;
import com.xingren.spring.exception.XrExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Slf4j
@ControllerAdvice
public class AdminExceptionHandler {

    @Autowired
    private XrExceptionHandler exceptionHandler;

    /**
     * 捕获所有异常
     */
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResponseEntity<?> handleAllException(HttpServletRequest request,
                                                HttpServletResponse response,
                                                Throwable error) {

        JsonResult json =  exceptionHandler.handleException(request, response, error);

        ResponseEntity.BodyBuilder resp = ResponseEntity.status(response.getStatus());
        if (_isJsonRequest(request)) {
            return resp.body(json);
        } else {
            // 如有必要，可以 Forward 到一个错误页面；或者定义一个 ErrorController 和 error 页面。
            String errMsg = String.format("出错啦：%s", json.getErrMessage().orElse("未知错误！"));
            return resp.body(errMsg);
        }
    }


    /**
     * 判断请求是否支持返回 Json
     */
    private boolean _isJsonRequest(HttpServletRequest request) {
        return request.getHeader("Accept").contains("json");
    }

}
